package com.example.ecommerce.controller;

import com.example.ecommerce.entity.User;
import com.example.ecommerce.service.OrderService;
import com.example.ecommerce.service.ProductService;
import com.example.ecommerce.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;


    @GetMapping("/users-with-stats")
    public Map<String, Object> getUsersWithStats() {
        Map<String, Object> result = new HashMap<>();
        List<User> users = userService.getAllUsersWithStats();
        result.put("data", users);
        result.put("success", true);
        return result;
    }

    @GetMapping("/user-orders/{uid}")
    public Map<String, Object> getUserOrders(@PathVariable Long uid) {
        Map<String, Object> result = new HashMap<>();
        result.put("data", userService.getUserOrders(uid));
        result.put("success", true);
        return result;
    }

    @GetMapping("/merchant-products/{uid}")
    public Map<String, Object> getMerchantProducts(@PathVariable Long uid) {
        Map<String, Object> result = new HashMap<>();
        result.put("data", userService.getMerchantProducts(uid));
        result.put("success", true);
        return result;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> userMap) {
        String username = userMap.get("username");
        String password = userMap.get("password");

        User user = userService.login(username, password);

        Map<String, Object> result = new HashMap<>();
        if (user != null) {
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("user", user);
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        }
        return result;
    }
    @GetMapping("/users")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @DeleteMapping("/users/{id}")
    public Map<String, Object> deleteUser(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 先获取用户信息用于返回更详细的提示
            User user = userService.getUserById(id);
            if (user == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }

            // 执行删除
            boolean success = userService.deleteUser(id);

            result.put("success", success);
            result.put("message", success ? "用户及其关联数据删除成功" : "删除失败");
            result.put("user", user);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        boolean success = userService.register(user);
        if (success) {
            result.put("success", true);
            result.put("message", "注册成功");
        } else {
            result.put("success", false);
            result.put("message", "用户名已存在");
        }

        return result;
    }

    @DeleteMapping("/user-orders/all/{userId}")
    public Map<String, Object> deleteAllUserOrders(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            int count = orderService.deleteByUserId(userId);
            result.put("success", true);
            result.put("message", "成功删除" + count + "条订单记录");
            result.put("count", count);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @DeleteMapping("/merchant-products/all/{merchantId}")
    public Map<String, Object> deleteAllMerchantProducts(@PathVariable Long merchantId) {
        Map<String, Object> result = new HashMap<>();
        try {
            int count = productService.deleteByMerchantId(merchantId);
            result.put("success", true);
            result.put("message", "成功删除" + count + "件商品");
            result.put("count", count);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }
    @GetMapping("/users/search")
    public Map<String, Object> searchUsers(@RequestParam String q) {
        Map<String, Object> result = new HashMap<>();
        List<User> users = userService.searchUsers(q);
        result.put("data", users);
        result.put("success", true);
        return result;
    }

    // 新增用户更新接口
    @PutMapping("/users/{id}")
    public Map<String,Object> updateUser(@PathVariable long id,@RequestBody User user){
        Map<String,Object> result = new HashMap<>();
        try{
            user.setId(id);
            boolean success = userService.updateUser(user);
            result.put("success",success);
            result.put("message",success?"用户更新信息成功":"更新失败");
            if(success){
                result.put("user",userService.getUserById(id));
            }
        }catch (Exception e){
            result.put("success",false);
            result.put("success",e.getMessage());
        }
        return result;
    }
}

